<template>
  <!-- 歌单详情 -->
  <div class="play-list-detail mtop-20">
    <el-skeleton :loading="isLoading" animated>
      <!-- 骨架 -->
      <template v-if="!isPhone" slot="template">
        <el-skeleton-item variant="image" style="width: 180px; height: 180px" />
        <div style="padding-top: 14px">
          <el-skeleton-item variant="text" style="width: 50%" />
          <div style="
              display: flex;
              align-items: center;
              justify-items: space-between;
              margin-top: 16px;
              height: 16px;
            ">
            <el-skeleton-item variant="text" style="margin-right: 16px" />
            <el-skeleton-item variant="text" style="width: 30%" />
          </div>
        </div>
      </template>
      <template>
        <div>
          <!-- 歌单图片及信息 -->
          <div class="detail-desc">
            <!-- 歌单图片 -->
            <div class="detail-img-wrapper">
              <img class="img img-radius-8 img-border" v-lazy="ImgUrl" />
            </div>
            <!-- 歌单信息 -->
            <div class="detail-desc-info">
              <div class="info-title">
                <Tag text="歌单"></Tag>
                <span class="mleft-12 font-20 font-bold">{{ info.name }}</span>
                <!-- 修改歌单信息 -->
                <span @click="toPlayListEdit" v-if="showEditIcon" class="mleft-10 font-18 pointer" style="color: #a3a3a3">
                  <i class="el-icon-edit"></i>
                </span>
                <!-- 删除歌单 -->
                <span @click="toPlayListDelete" v-if="showEditIcon" class="mleft-10 font-18 pointer"
                  style="color: #a3a3a3">
                  <i class="el-icon-delete"></i>
                </span>
              </div>
              <div class="author">
                <div class="author-img pointer" @click="toUserDetail(info)">
                  <img class="img-h circle" :src="avatarUrl" />
                </div>
                <div class="author-info">
                  <span class="mleft-12 font-12 pointer" @click="toUserDetail(info)" style="color: #0b58b0">{{
                    creator.nickname }}</span>
                  <span class="mleft-12 font-12">{{
                    info.createTime | dateFormat
                  }}</span>
                </div>
                <!-- 歌单按钮 -->
                <ul class="info-btn">
                  <button class="btn btn-blue" @click="playAll" :disabled="this.playList.length === 0">
                    <i class="iconfont icon-bofang"></i>
                    <span class="btn-text">&nbsp;&nbsp;播放全部</span>
                  </button>
                  <!-- 中间的隔离层  TODO:这里是收藏歌单操作的地方，需要去解决！！！-->
                  <span style="display: inline-block;width: 16px;"></span>
                  <button v-show="!isSameUUID"  class="btn btn-grey" style="align-items: center;width: 106px;" @click="collect(info)">
                    <i v-if="info.favorites" class="iconfont icon-shoucang1"></i>
                    <i v-else class="iconfont icon-weishoucang"></i>
                    <span class="btn-text">&nbsp;&nbsp;{{ info.favorites ? '取消收藏' : '收藏' }}</span>
                  </button>
                </ul>
              </div>

              <div class="detail-tag font-14" v-if="tags.length !== 0">
                <span>标签 ：</span>
                <span class="mright-10" v-for="(val, index) in tags" :key="index">{{ val }}</span>
              </div>
              <div class="num-info font-14">
                <span v-text="`歌曲 ：${info.tracks ? info.tracks.length : 0}`"></span>
              </div>
              <!-- 歌单描述 -->
              <div class="font-14 relative">
                <input id="check" type="checkbox" />
                <div class="element">
                  <p id="p-desc" style="max-width: 1000px" v-text="`简介 ：${info.description === null || info.description === ''
                    ? '什么都没有介绍'
                    : info.description
                    }`
                    "></p>
                </div>
                <label for="check" class="check-in" v-show="isShowDescExpandIcon"><i
                    class="iconfont icon-zhankai"></i></label>
                <label for="check" class="check-out"><i class="iconfont icon-shouqi"></i></label>
              </div>
            </div>
          </div>
          <!-- 歌单列表 -->
          <div class="detail-head">
            <TabMenu @menuClick="handlerView" :menuList="['歌曲列表', '歌单评论']"></TabMenu>
            <div class="detail-search" v-show="showtab === 1">
              <el-input placeholder="搜索音乐" clearable suffix-icon="el-icon-search" v-model="key"></el-input>
            </div>
          </div>
          <div v-show="showtab === 1">
            <MusicList @updateNum="change" ref="listRef" :list="list" :currentPlayListId="id"></MusicList>
          </div>
          <!-- 歌单评论 -->
          <div v-show="showtab === 2">
            <!-- 这里写一点评论框 -->
            <div class="stick">
              <!-- 最外层评论 -->
              <Remark @publish="publishRemark" @success="clearRemark = false" :clear="clearRemark"></Remark>
            </div>
            <MessageList @refresh="getPlayListRemark" :listId="id" :name="info.name" :list="messageLists"></MessageList>
            <el-empty :image-size="100" v-show="messageLists.length === 0" description="暂无评论"></el-empty>
          </div>
        </div>
      </template>
    </el-skeleton>
  </div>
</template>

<script>
/* test：做mock服务的请求数据 */
// import axios from "axios"

import MusicList from "@/components/list/MusicList";
import TabMenu from "@/components/menu/TabMenu";
import Tag from "@/components/simple/Tag";
import Remark from "@/components/simple/Remark.vue"
import MessageList from "@/components/list/MessageList.vue";
import { getPlayListDetail, deletePlayList, getAllComment, addComment,addFavorites ,removeFavorites } from "@/api/api_playlist";
import { mapState } from "vuex"
export default {
  props: {
    id: {
      type: String,
      required: true,
    },
  },
  components: {
    MusicList,
    TabMenu,
    Tag,
    MessageList,
    Remark
  },
  data() {
    return {
      info: {},
      key: "",
      playList: [],
      showtab: 1,
      creator: {},
      tags: [],
      suberList: [],
      pageInfo: {
        currentPage: 1,
        total: 0,
      },
      isLoading: true,
      isSubloading: true,
      isShowDescExpandIcon: false,
      isPub: false,
      uuid: '',
      messageLists: [],
      clearRemark: false
    };
  },
  computed: {
    ...mapState(["isLogin", "profile", "isPhone"]),

    list() {
      let reg = new RegExp(this.key.trim(), "ig");
      return this.playList.filter((item) => {
        return item.title.match(reg);
      });
    },
    subDisabled() {
      if (this.isLogin) return this.info.userId === this.profile.userId;
      else return false;
    },
    ImgUrl() {
      return this.info.coverImgUrl
        ? `${this.info.coverImgUrl}?param=300y300`
        : "";
    },
    avatarUrl() {
      return this.creator.avatarUrl
        ? this.creator.avatarUrl
        : require("../../assets/img/avatar.jpeg");
    },
    showEditIcon() {
      return this.isLogin && this.profile.userId === this.creator.userId && this.isSameUUID;
    },
    isSameUUID() {
      let userUUID = JSON.parse(localStorage.getItem("profile")).data.uuid;
      return userUUID === this.uuid;
    },
  },
  watch: {
    id() {
      this.showtab = 1;//放在监视属性改变一下就行了
      this.getPlayList();
      this.getPlayListRemark();
    },
  },
  created() {
    this.getPlayList();
    this.getPlayListRemark();
    /* mock数据 */
    // axios.get("/json/message.json").then((val) => {
    //   let { data } = val;
    //   this.messageLists = data
    // })
  },
  beforeRouteEnter(to, from, next) {
    //这里解决了路由从首页图片跳转过来 isPublic 为true;可以进行下面判断的操作了
    let isPublic = from.meta.isPublic ?? false;
    //这里得将isPublic路由元信息改为false
    //本来这里是要解决那个其他用户访问公共歌单不去修改推送歌单用户的歌单信息！！！
    next(vm => {
      if (isPublic) {//可以将那两个修改和删除图标进行隐藏了
        vm.isPub = isPublic
      }
      from.meta.isPublic = false;
    });//放行
  },
  methods: {
    /* 获取歌单信息 */
    async getPlayList() {
      let uuid = JSON.parse(localStorage.getItem("profile")).data.uuid;
      this.isLoading = true;
      let res = await getPlayListDetail(uuid,this.id);
      res = { code: res.code, msg: res.msg, ...res.data };
      this.uuid = res.uuid;
      if (res.code !== 200) return;
      this.info = res;//Object.freeze(res)
      this.tags = Object.freeze(res.tags ? res.tags : []);
      this.creator = Object.freeze(res.creator);

      this.playList = Object.freeze(res.tracks);
      this.isLoading = false;
      this.$nextTick(() => {
        const h = document.querySelector("#p-desc").offsetHeight;
        if (h > 24) {
          this.isShowDescExpandIcon = true;
        } else {
          this.isShowDescExpandIcon = false;
        }
      });
    },
    /* 获取歌单评论信息 */
    async getPlayListRemark() {
      let uuid = JSON.parse(localStorage.getItem("profile")).data.uuid;
      let res = await getAllComment(uuid,this.id);//传入一个listId
      //进行数据的回显
      let { data } = res;
      if (data) {
        //根据时间进行排序,其实id一直是自增长的，所以用一下id
        data.sort((a, b) => b.id - a.id);
        this.messageLists = data;
      }
    },
    /* 页码变化的回调 */
    handleCurrentChange(val) {
      this.pageInfo.currentPage = val;
      document.querySelector(".main-right").scrollTop = 0;
    },
    playAll() {
      /* 访问音乐列表组件的方法 */
      this.$refs.listRef.playMusicAll();
    },
    toUserDetail(item) {
      let uuid = JSON.parse(localStorage.getItem("profile")).data.uuid;
      if (uuid == item.uuid) this.$router.push("/userdetail/")
      else {//跳转到其他用户的详细信息界面
          this.$router.push("/userdetail/"+String(item.uuid));
      }
    },

    toPlayListEdit() {
      this.$router.push("/playlistedit/" + this.id);
    },
    toPlayListDelete() {
      this.$confirm("此操作将删除该歌单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            id: this.id,
            token: localStorage.getItem("token"),
          };
          const res = await deletePlayList(params);
          if (res.data.code !== 200) {
            this.$message({ type: "warning", message: "删除失败" });
            return;
          }
          this.$store.dispatch("getMyPlayList");
          this.$message({ type: "success", message: "删除成功" });
          this.$router.push("/personalrecom");
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    change(tracks) {
      //修改Num的数值
      this.info.tracks = tracks
    },
    handlerView(index) {//其实这里只有两个不用多去管他
      this.showtab = index + 1;
    },
    async publishRemark(remark) {
      //这里向特点的歌单下增加一条主要评论
      //其中要携带UUID，歌单listId
      let uuid = JSON.parse(localStorage.getItem("profile")).data.uuid;
      let res = await addComment(uuid, remark, this.id);
      //后端交互，成功给出提示！
      if (res.code == 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.clearRemark = true;
        this.getPlayListRemark();//再次获取！！！
      } else {
        this.$message.error(res.msg);
        this.clearRemark = false;
      }
    },
    async collect(info){
      let uuid = JSON.parse(localStorage.getItem("profile")).data.uuid;
      //如果收藏的状态是收藏的，添加到侧边栏中！
      let res;
      if(info.favorites){//已经收藏，那就取消
        res=await removeFavorites(uuid,this.id);
      }else{//进行收藏
        res=await addFavorites(uuid,this.id);
      }
      this.$store.dispatch("getcollectPlayList")
     info.favorites=!info.favorites//先将确定是否收藏或者取消收藏！
    }
  },
};
</script>

<style lang="less" scoped>
.relative {
  position: relative;
}

/* 歌单信息区域 */
.detail-desc {
  display: flex;

  .detail-img-wrapper {
    width: 180px;
    height: 180px;
  }

  .detail-desc-info {
    line-height: 24px;
    margin-left: 20px;

    .author {
      margin: 15px 0;
      height: 24px;
      display: flex;

      .author-img {
        height: 24px;
      }
    }

    .info-btn {
      position: relative;
      bottom: 5px;
      margin-left: 15px;
    }
  }
}

/* 列表头部区域 */
.detail-head {
  display: flex;
  // background-color: #fff;
  justify-content: space-between;
  align-items: center;
}

/* 文字展开收起效果 */
.element {
  max-height: 20px;
  overflow: hidden;
  transition: max-height 1s;
}

:checked~.element {
  max-height: 666px;
}

input[type="checkbox"] {
  position: absolute;
  clip: rect(0 0 0 0);
}

:checked~.check-in {
  display: none;
}

:checked~.check-out {
  display: inline-block;
}

.check-out {
  display: none;
}

.check-in,
.check-out {
  position: absolute;
  right: -12px;
  top: -2px;
  color: #34538b;
  cursor: pointer;
}

.comment {
  background-color: #fff;
}

@media screen and (max-width: 768px) {
  .detail-desc {
    display: block;
    position: relative;

    .detail-img-wrapper {
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0.5;
      border-radius: 8px;
      overflow: hidden;

      img {
        transform: translateY(-20%);
        border: none;
      }
    }

    .detail-desc-info {
      padding-top: 10px;
    }
  }

  /* .detail-search {
      display: none;
    } */
  .info-btn {
    display: flex;
    flex-wrap: wrap;

    .btn {
      margin: 5px;
    }
  }
}

@media screen and (max-width: 415px) {
  .detail-desc {
    display: block;
    position: relative;

    .detail-img-wrapper {
      img {
        transform: none;
      }
    }

    .detail-desc-info {
      min-height: 60vw;
      position: relative;
    }
  }

  .detail-search {
    display: none;
  }
}

.stick {
  position: sticky;
  top: 0px;
  z-index: 1000;
}
</style>
